package com.edu.boot.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.edu.boot.common.MD5Utils;
import com.edu.boot.common.UUIDUtils;
import com.edu.boot.common.api.CommonResult;
import com.edu.boot.config.UserContext;
import com.edu.boot.entity.*;
import com.edu.boot.entity.Vo.*;
import com.edu.boot.enums.OfferStatus;
import com.edu.boot.mapper.NotesManageMapper;
import com.edu.boot.service.CommentReplyService;
import com.edu.boot.service.CommentService;
import com.edu.boot.service.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class StudentController {
    @Autowired
    UserService stuUserService;
    @Autowired
    RecruitmentService recruitmentService;
    @Autowired
    BusinessShopService businessShopService;
    @Autowired
    RecuritTypeService recuritTypeService;
    @Autowired
    BannerService bannerService;
    @Autowired
    SResumeService sResumeService;

    @Autowired
    UserService userService;
    @Value("${ip:localhost}")
    String ip;
    @Value("${server.port}")
    String port;

    /**
     * 获取所有简历 以及 主人-商店详细
     *
     * @return
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/getrec")
    public CommonResult getRec() {
        Users user = UserContext.getUser();
        List<RecruitmentAllInfoVo> userAllInfo = recruitmentService.getUserAllInfo();
        if (CollectionUtil.isNotEmpty(userAllInfo)){
            Map<Integer, String> recuritTypeMap = recuritTypeService.getRecuritTypeMap();
            userAllInfo = userAllInfo.stream().map(item->{
                item.setRecTypeMsg(recuritTypeMap.get(item.getRecType()));
                return item;
            }).collect(Collectors.toList());
        }
        return CommonResult.success(userAllInfo, "获取招聘信息成功！");
    }

    /**
     * 根据id获取招聘详细信息
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/recshow/{id}")
    public CommonResult getRecInfoByid(@PathVariable Integer id) {
        RecruitmentAllInfoVo userAllShopRecruitmentInfoByRid = recruitmentService.getUserAllShopRecruitmentInfoByRid(id);
        return CommonResult.success(userAllShopRecruitmentInfoByRid, "获取招聘详细信息成功！");
    }

    /**
     * 搜索职位关键字返回前端 所有信息
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/search/{search}")
    public CommonResult searchRecInfo(@PathVariable String search) {
        List<RecruitmentAllInfoVo> userAllInfoSearch = recruitmentService.getUserAllInfoSearch(search);
        if (userAllInfoSearch.isEmpty()) return CommonResult.failed("未搜索到关键字信息！");
        return CommonResult.success(userAllInfoSearch, "搜索成功！");
    }


    /**
     * 前端点击访问某个招聘页面，就给这个招聘信息热度+1
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/addheat/{rid}")
    public CommonResult AddRecHeat(@PathVariable Integer rid) {
        UpdateWrapper<Recruitment> recruitmentUpdateWrapper = new UpdateWrapper<>();
        recruitmentUpdateWrapper.eq("rec_id", rid);
        recruitmentUpdateWrapper.setSql("`rec_heat` = `rec_heat` + 1");
        // 更新
        boolean update = recruitmentService.update(recruitmentUpdateWrapper);
        if (!update) return CommonResult.failed("该招聘热度未增加！");
        return CommonResult.success(null, "热度增加!");
    }


    /**
     * 前端轮播图 头条数据获取
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/bannertop")
    public CommonResult getTop() {
        List<Banner> bannerTopList = bannerService.list();
        SResume resume = sResumeService.getResumeByUId(UserContext.getUserId());
        if(Objects.nonNull(resume)){
            Integer recType = resume.getRecType();
            List<Recruitment> recruitmentList = recruitmentService.getByRecType(recType);
                for(int  i = 0; i < bannerTopList.size(); i++){
                    Banner banner = bannerTopList.get(i);
                    if(Objects.nonNull(recruitmentList) && recruitmentList.size() > i){
                        banner.setTopTitle(recruitmentList.get(i).getRecName()+ "    " + recruitmentList.get(i).getRecStation());
                        banner.setBannerUrl("/suthome/recshow/" + recruitmentList.get(i).getRecId());
                    }
                }
        }
        if (bannerTopList.isEmpty()) return CommonResult.failed("未获取到头条数据！");
        return CommonResult.success(bannerTopList, "获取头条成功!");
    }

    /**
     * 个人中心
     */
    @ResponseBody
    @GetMapping("suthome/stuindex/myinfo")
    public CommonResult getInfo(@RequestParam(name = "uid") Integer uid) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid).select("uid", "username","nickname", "image_data", "create_time", "mobile", "email",
                                      "age", "pid");
        Users list = stuUserService.getOne(wrapper);

        if (list == null) return CommonResult.failed("未获取到个人数据！");
        return CommonResult.success(list, "获取成功!");
    }

    /**
     * 通过ID修改学生头像
     *
     * @return
     */
    @ResponseBody
    @PostMapping("stu/editimg")
    public CommonResult stuEditImg(@RequestBody Users users) {
        UpdateWrapper<Users> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("uid", users.getUid());
        usersUpdateWrapper.set("image_data", users.getImageData());
        boolean update = stuUserService.update(users, usersUpdateWrapper);
        if (!update) return CommonResult.failed("修改失败！！");
        return CommonResult.success(null, "修改成功！！");
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @PostMapping("stu/edit/password")
    public CommonResult stuEditPassword(@RequestBody EditPasswordVo editPasswordVo) {
        //判断传递来的是否一样
        if (Objects.equals(editPasswordVo.getOldPassword(), editPasswordVo.getPassword()))
            return CommonResult.failed("密码不能一致！！");
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        //通过uid得到原本的盐
        wrapper.eq("uid", editPasswordVo.getUid());
        String salt = stuUserService.getOne(wrapper).getSalt();

        //原本加密手段之后去对比
        String s = MD5Utils.md5(editPasswordVo.getOldPassword() + salt);
        wrapper.eq("password", s);
        Users one = stuUserService.getOne(wrapper);
        //如果对比错误就不一样
        if (one == null) return CommonResult.failed("旧密码错误！！");
        //对比成功就初始化盐
        salt = UUIDUtils.getUUID();

        UpdateWrapper<Users> usersUpdateWrapper = new UpdateWrapper<>();
        //新的密码 加密
        String newPass = MD5Utils.md5(editPasswordVo.getPassword() + salt);
        usersUpdateWrapper.eq("uid", editPasswordVo.getUid());
        //存新盐
        usersUpdateWrapper.set("salt", salt);
        //新密码
        usersUpdateWrapper.set("password", newPass);
        boolean update = stuUserService.update(usersUpdateWrapper);
        if (!update) return CommonResult.failed("修改密码失败！！");
        return CommonResult.success(null, "修改密码成功！！");
    }


    //获取项目根目录路径
    //以及文件要存储目录
    private static final String ROOT_PATH =  System.getProperty("user.dir") + File.separator + "files";
    
    /**
     * 获取简历
     */
    @ResponseBody
    @GetMapping("stu/notes/{uid}")
    public CommonResult getNotes(@PathVariable Integer uid){
        QueryWrapper<SResume> sResumeQueryWrapper = new QueryWrapper<>();
        sResumeQueryWrapper.eq("u_id",uid);
        // 获取简历
        List<SResume> list = sResumeService.list(sResumeQueryWrapper);

        if (list.isEmpty()) return CommonResult.failed("当前无简历，请您添加！！");

        return CommonResult.success(list,"获取简历成功！！");
    }

    

    /**
     * 删除简历
     */
    @ResponseBody
    @PostMapping("stu/notes/del")
    public CommonResult delNotes(@RequestParam(name = "uid") Integer uid,@RequestParam(name = "fileName") String fileName){
        

        QueryWrapper<SResume> sResumeQueryWrapper = new QueryWrapper<>();
        //名字已经确保不重复
        sResumeQueryWrapper.eq("uid",uid).eq("filename",fileName);

        boolean remove = sResumeService.remove(sResumeQueryWrapper);
        if (!remove) return CommonResult.failed("删除简历失败！！");
        return CommonResult.success(null,"删除简历成功！！");
    }



    /**
     * 投递简历
     * 直接存储这学生的uid、简历t_id、某个招聘rec_id
     */
    @Autowired
    NotesManageService notesManageService;
    @Autowired
    NotesManageMapper notesManageMapper;

    @ResponseBody
    @PostMapping("stu/notes/send")
    public CommonResult sendNotes(@RequestBody NotesManage notesManage){
        //判断一个学生投了同一个招聘，不给投 返回每份简历只能投一次
        notesManage.setUid(UserContext.getUserId());
        notesManage.setCreateTime(DateUtil.date());
        notesManage.setOfferStatus(OfferStatus.YTD.getCode());
        Integer size =  notesManageService.getMyNotesCount(notesManage.getUid(),notesManage.getRecId());
        System.out.println(size);
        if (size >= 1) return CommonResult.failed("您已投递简历，请勿重复投递！！");
        // 投递简历
        boolean save = notesManageService.save(notesManage);
        if (!save) return CommonResult.failed("投递简历失败！！");
        return CommonResult.success(null,"投递简历成功！");
    }







    @Autowired
    CommentService commentService;
    @Autowired
    CommentReplyService commentReplyService;

    /**
     * 通过简历id展现出对应的评论
     */
    @ResponseBody
    @GetMapping("stu/rec/comment/{rid}")
    public CommonResult commentShowByRecId(@PathVariable Integer rid)  {
        QueryWrapper<CommentAndChildrenVo> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("rec_id",rid);

        List<CommentAndChildrenVo> commentByRid = commentService.getCommentByRid(rid);
        if (commentByRid.isEmpty()) return CommonResult.failed("当前简历无评论");
        for (CommentAndChildrenVo commentAndChildrenVo : commentByRid) {
            //获取某个父级评论的所有子评论 存入
            List<CommentReplyAndUserInfoVo> commentReplyByCid = commentService.getCommentReplyByCid(commentAndChildrenVo.getComId());
            commentAndChildrenVo.setChildren(commentReplyByCid);
        }
        //返回前端
        return CommonResult.success(commentByRid,"获取评论成功");
    }

    /**
     * 增加一级评论
     */
    @ResponseBody
    @PostMapping("stu/rec/add/comment")
    public CommonResult addComment(@RequestBody Comment comment)  {
        comment.setCreateTime(null);
        comment.setComId(null);
        // 保存
        boolean save = commentService.save(comment);
        if (!save)  return CommonResult.failed("添加评论失败");
        return CommonResult.success(null,"添加评论成功");
    }


    /**
     * 增加二级评论 前端把com_id存入answer_id 外键
     */
    @ResponseBody
    @PostMapping("stu/rec/add/reply")
    public CommonResult addCommentReply(@RequestBody CommentReply comment)  {
        System.out.println(comment);
        comment.setCreateTime(null);
        comment.setRepId(null);
        boolean save = commentReplyService.save(comment);
        if (!save)  return CommonResult.failed("添加评论失败");
        return CommonResult.success(null,"添加评论成功");
    }

    /**
     * 删除指定父级评论
     */
    @ResponseBody
    @GetMapping("stu/rec/del/comment/{cid}")
    public CommonResult delComment(@PathVariable Integer cid)  {
        //先删除 子评论 再删除父级评论
        QueryWrapper<CommentReply> commentReplyQueryWrapper = new QueryWrapper<>();
        commentReplyQueryWrapper.eq("answer_id",cid);
        commentReplyService.remove(commentReplyQueryWrapper);

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("com_id",cid);

        boolean remove = commentService.remove(commentQueryWrapper);
        if (!remove)  return CommonResult.failed("删除评论失败");

        return CommonResult.success(null,"删除评论成功");
    }


    /**
     * 删除指定子级评论
     */
    @ResponseBody
    @GetMapping("stu/rec/del/reply/{rid}")
    public CommonResult delCommentReply(@PathVariable Integer rid)  {
        //先删除 子评论 再删除父级评论
        QueryWrapper<CommentReply> commentReplyQueryWrapper = new QueryWrapper<>();
        commentReplyQueryWrapper.eq("rep_id",rid);
        boolean remove = commentReplyService.remove(commentReplyQueryWrapper);
        if (!remove)  return CommonResult.failed("删除评论失败");

        return CommonResult.success(null,"删除评论成功");
    }
    
    /**
     * 获取学生投递的简历信息
     * 该方法会返回学生投递的所有简历信息，包括：
     * 1. 每个招聘岗位的详细信息
     * 2. 投递的简历状态
     * 3. 企业方的反馈信息
     * 4. 招聘类型信息
     *
     * 主要调用方法：
     * - notesManageService.list(): 获取学生投递的所有简历记录
     * - sResumeService.getOneTid(): 获取简历详细信息
     * - userService.getQyMap(): 获取企业ID到企业名称的映射
     * - recuritTypeService.getRecuritTypeMap(): 获取招聘类型ID到类型名称的映射
     * - recruitmentService.getOne(): 获取招聘岗位详细信息
     *
     * @param uid 学生用户ID
     * @return 返回包含招聘信息和投递简历状态的列表
     */
    @ResponseBody
    @GetMapping("stu/deliver/{uid}")
    public CommonResult getMyDeliver(@PathVariable Integer uid)  {
        // 创建查询条件，根据当前登录用户ID查询
        QueryWrapper<NotesManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",UserContext.getUserId());
        //获取学生自己投递的简历
        List<NotesManage> list1 = notesManageService.list(queryWrapper);
        
        // 创建Map用于存储招聘ID和对应的简历列表
        HashMap<Integer, ArrayList<SResumeAndNid>> map = new HashMap<>();
        // 创建最终返回的招聘信息列表
        List<RecruitmentAndSonNotesManageVo> recruitmentAndSonNotesManageVos = new ArrayList<>();
        // 获取企业ID到企业名称的映射
        Map<Integer, String> qyMap = userService.getQyMap();
        
        //遍历所有这企业旗下的收到的简历
        for (NotesManage notesManage : list1) {
            //如果Map集合中recid不存在就创建recid 指向 这招聘信息的所有简历
            if(!map.containsKey(notesManage.getRecId())){
                //获取这次不重复招聘信息 的 学生简历
                SResumeAndNid sResume = sResumeService.getOneTid(notesManage.getResumeId());
                // 设置简历相关信息
                sResume.setNid(notesManage.getNid());
                sResume.setOfferStatus(notesManage.getOfferStatus());
                sResume.setComment(notesManage.getComment());
                sResume.setResult(notesManage.getResult());
                sResume.setQyId(notesManage.getQyId());
                sResume.setNickName(qyMap.get(notesManage.getQyId()));
                sResume.setResumeId(notesManage.getResumeId());
                sResume.setRecId(notesManage.getRecId());
                // 创建新的简历列表并添加当前简历
                ArrayList<SResumeAndNid> sResumeLists = new ArrayList<>();
                sResumeLists.add(sResume);
                //存放到map中
                map.put(notesManage.getRecId(),sResumeLists);
            }else {
                //如果map中已经存在这简历了就要获取这map的学生简历，然后追加新的学生简历，再重置这集合
                ArrayList<SResumeAndNid> sResumes = map.get(notesManage.getRecId());
                ArrayList<SResumeAndNid> newsResumes = new ArrayList<>();
                // 获取新的简历信息
                SResumeAndNid sResume = sResumeService.getOneTid(notesManage.getResumeId());
                // 设置简历相关信息
                sResume.setNid(notesManage.getNid());
                sResume.setOfferStatus(notesManage.getOfferStatus());
                sResume.setComment(notesManage.getComment());
                sResume.setResult(notesManage.getResult());
                sResume.setQyId(notesManage.getQyId());
                sResume.setNickName(qyMap.get(notesManage.getQyId()));
                sResume.setResumeId(notesManage.getResumeId());
                sResume.setRecId(notesManage.getRecId());
                // 合并现有简历列表和新简历
                newsResumes.addAll(sResumes);
                newsResumes.add(sResume);
                map.put(notesManage.getRecId(),newsResumes);
            }
        }
        
        // 获取招聘类型ID到类型名称的映射
        Map<Integer, String> recuritTypeMap = recuritTypeService.getRecuritTypeMap();
        RecruitmentAndSonNotesManageVo recruitmentAndSonNotesManageVo = null;
        
        // 遍历所有招聘ID，构建最终的返回数据
        for (Object o : map.keySet().toArray()) {
            recruitmentAndSonNotesManageVo = new RecruitmentAndSonNotesManageVo();
            // 查询招聘信息
            QueryWrapper<Recruitment> recruitmentQueryWrapper = new QueryWrapper<>();
            recruitmentQueryWrapper.eq("rec_id",(Integer) o);
            final Recruitment byId = recruitmentService.getOne(recruitmentQueryWrapper);
            
            // 设置招聘信息
            recruitmentAndSonNotesManageVo.setRecSalary(byId.getRecSalary());
            recruitmentAndSonNotesManageVo.setRecInfo(byId.getRecInfo());
            recruitmentAndSonNotesManageVo.setRecId(byId.getRecId());
            recruitmentAndSonNotesManageVo.setRecHeat(byId.getRecHeat());
            recruitmentAndSonNotesManageVo.setRecName(byId.getRecName());
            recruitmentAndSonNotesManageVo.setRecType(byId.getRecType());
            recruitmentAndSonNotesManageVo.setRecTypeMsg(recuritTypeMap.get(byId.getRecType()));
            recruitmentAndSonNotesManageVo.setRecStation(byId.getRecStation());

            // 设置该招聘下的所有简历信息
            ArrayList<SResumeAndNid> sResumes = new ArrayList<>();
            sResumes.addAll(map.get(o));
            recruitmentAndSonNotesManageVo.setChildren(sResumes);

            // 添加到最终返回列表
            recruitmentAndSonNotesManageVos.add(recruitmentAndSonNotesManageVo);
        }
        return CommonResult.success(recruitmentAndSonNotesManageVos,"....");
    }
}
